package com.xingchen.feima.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xingchen.feima.common.utils.MD5;
import com.xingchen.feima.common.utils.R;
import com.xingchen.feima.common.entity.User;
import com.xingchen.feima.common.entity.vo.LoginVo;
import com.xingchen.feima.system.service.UserService;
import com.xingchen.feima.common.utils.JwtHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "登录、获取用户信息和退出管理")
@RestController
@RequestMapping("/system/index")
public class IndexController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public R login(
            @ApiParam(name = "loginVo", value = "登录对象", required = true)
            @RequestBody LoginVo loginVo) {

        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginVo.getUsername()));
        if(user == null) {
            return R.error().message("账号不存在");
        }
        if(!MD5.encrypt(loginVo.getPassword()).equals(user.getPassword())) {
            return R.error().message("密码错误");
        }
        if(user.getStatus().equals(0)) {
            return R.error().message("账号停用");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("token", JwtHelper.createToken(user.getId(), user.getUsername()));
        return R.ok().data("items", map);
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping("/userInfo")
    public R getUserInfo(HttpServletRequest request) {
        String username = JwtHelper.getUsername(request.getHeader("token"));
        Map<String, Object> map = userService.getUserInfo(username);
        return R.ok().data("items", map);
    }

    @ApiOperation(value = "退出")
    @PostMapping("/logout")
    public R logout(){
        return R.ok();
    }
}
